<template>
  <smart-form
    ref="formRef"
    :fields="formFields"
    :form-data="formData"
    @update:value="updateData"
  />

  <div class="form-actions">
    <el-button @click="resetForm">重置</el-button>
    <el-button type="primary" @click="submitForm">登录</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();

const formData = ref({
  username: "",
  password: "",
});
const formRef = ref();

// 表单配置
const formFields = [
  {
    type: "input",
    label: "用户名",
    name: "username",
    attrs: {
      placeholder: "请输入用户名",
    },
    rules: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  },
  {
    type: "input",
    label: "密码",
    name: "password",
    attrs: {
      placeholder: "请输入密码",
      inputType: "password",
      showPassword: true,
      clearable: true,
    },
    rules: [{ required: true, message: "密码不能为空", trigger: "blur" }],
  },
];

// 数据更新回调
const updateData = (val: object) => {
  console.log("表单数据更新:", val);
};

// 重置表单
const resetForm = () => {
  formRef.value.reset();
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    const data = formRef.value?.getFormData();
    router.push("/");
    // 这里可以添加提交逻辑
    if (data.username === "admin" && data.password === "admin") {
      router.push("/home.html");
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};
</script>

<style scoped>
.form-container {
  max-width: 600px;
  margin: 20px auto;
}
.form-actions {
  margin-top: 20px;
  text-align: center;
}
</style>
